package org.example.springboot.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.springboot.component.SseEmitterServer;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

/**
 * SseController
 *
 * @author fz
 * 2024/3/26 11:18
 **/
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/sse")
public class SSEController {

    @Resource
    private SseEmitterServer sseEmitterServer;

    /**
     * 客户端连接 SSE 端点
     *
     * @return SseEmitter
     */
    @GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect() {
        return sseEmitterServer.connect();
    }

    /**
     * 向所有客户端广播消息
     *
     * @param message 消息内容
     * @return 通知结果
     */
    @PostMapping("/broadcast")
    public String broadcast(@RequestParam String message) {
        return sseEmitterServer.broadcast(message);
    }

}